<!--
 * @Author: zhangjingyu
 * @Date: 2020-11-04 19:43:11
 * @LastEditors: zhangjingyu
 * @LastEditTime: 2021-01-15 11:00:37
 * @Description: 曲线维护
-->
<template>
  <!-- 曲线维护页面 -->
  <div>
    <el-row class="caliberHierarchy container" :gutter="20">
      <!-- 左侧树 -->
      <el-col :span="6">
       
        <vp-tree
          class="ie-tree-style"
          :vp-header="{show:true,text:'曲线列表',search:true,name:'curveName'}"
          :vp-title="'所有曲线'"
          :filter-node-method="filterNode"
          :data="treeData"
          :props="defaultProps"
          @node-click="handleNodeClick"
          show-checkbox
          @check ="handleNodeClick"
          default-expand-all
          ref="configTree"
          node-key="curveCode"
          :expand-on-click-node="false"
          check-on-click-node
          :render-content="rendertree"
        ></vp-tree>
      </el-col>
      <!-- 右侧表  -->
      <el-col :span="18" class="content-left">
        <el-row class="handleBox">
          <el-col :span="18">
            <el-button @click="addFunc">新增</el-button>
            <el-button @click="editFunc">编辑</el-button>
            <el-button @click="delFunc">删除</el-button>
            <el-button @click="viewFunc">查看</el-button>
            <el-button @click="startOrBackFunc(1)">曲线确认</el-button>
            <el-button @click="startOrBackFunc(0)">取消确认</el-button>
            <!-- <el-button @click="spotCalculation()">即期计算</el-button> -->
          </el-col>
          <el-col :span="6">
            <div class="handleIconBox">
              <!-- <i class="iconfont icon-export" title="导出"></i> -->
              <!-- <i class="iconfont icon-import" title="导入"></i> -->
              <el-popover
                placement="bottom"
                trigger="click"
                popper-class="icon_porper"
              >
                <div class="search_porper">
                  <el-form
                    :model="searchForm"
                    ref="searchForm"
                    label-width="100px"
                    label-position="right"
                    size="mini"
                  >
                    <el-form-item label="数据日期：">
                      <el-date-picker
                        v-model="searchForm.dataDate"
                        type="date"
                        style="width:150px"
                        placeholder="选择日期"
                        value-format="yyyy-MM-dd"
                      >
                      </el-date-picker>
                    </el-form-item>
                  </el-form>

                  <div style="text-align:center;padding:10px">
                    <el-button size="mini" @click="searchForm.page=1,searchFunc()">查询</el-button>
                    <el-button
                      size="mini"
                      @click="
                        (searchForm.dataDate = '')
                      "
                      >重置</el-button
                    >
                  </div>
                </div>
                <i
                  class="iconfont icon-sousuo"
                  title="搜索"
                  slot="reference"
                ></i>
              </el-popover>
              <el-popover
                placement="bottom"
                width="150"
                trigger="click"
                popper-class="icon_porper"
              >
                <div class="operation_checkbox">
                  <el-checkbox-group v-model="checkList">
                    <el-checkbox
                      v-for="item in textData"
                      :label="item.label"
                      :key="item.prop"
                      >{{ item.label }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
                <i
                  class="iconfont icon-liebiaoshezhi"
                  title="列表设置"
                  slot="reference"
                ></i>
              </el-popover>
            </div>
          </el-col>
        </el-row>
        <el-table
          ref="multipleTable"
          :data="tableData"
          @row-click="authorizeFor"
        >
          <el-table-column
            width="55"
            type="selection"
            
          ></el-table-column>

          <el-table-column
            prop="CURVE_CODE"
            label="曲线编码"
            v-if="columnState[0]"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            prop="CURVE_NAME"
            label="曲线名称"
            sortable
            v-if="columnState[1]"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            prop="DATA_DATE"
            label="数据日期"
            sortable
            v-if="columnState[2]"
            align="right"
          >
          </el-table-column>
          <el-table-column
            prop="AFFIRM_DATE"
            label="确认日期"
            sortable
            v-if="columnState[3]"
            align="right"
            :formatter="row => row.AFFIRM_DATE || '-'"
          >
          </el-table-column>
          <template v-for="(head, index) in forDataList">
            <el-table-column
              :key="head.TERM_ID"
              :prop="'DATA' + (index + 1)"
              :label="head.TERM_VALUE + termTypes[head.TERM_UNIT]"
              :show-overflow-tooltip="true"
              :formatter="
                row =>
                  row['DATA' + (index + 1)]
                    ? (row['DATA' + (index + 1)] * 100).toFixed(6)
                    : '0'
              "
              align="right"
            >
            </el-table-column>
          </template>
        </el-table>
        <pagination
          @size-change="sizeChange"
          @current-change="pageChange"
          @refresh="searchFunc"
          :current-page="searchForm.page"
          :page-size="searchForm.size"
          :total="total"
        ></pagination>
      </el-col>
    </el-row>
    <el-dialog
      v-dialogDrag
      :title="saveTitles[saveFlg - 1]"
      :visible.sync="addOrEdit"
      width="514px"
    >
      <el-form
        :model="saveForm"
        ref="saveForm"
        label-width="140px"
        label-position="left"
        :disabled="saveFlg === 3"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item
              label="曲线名称："
              prop="curveName"
              :rules="[{ required: true, message: '曲线名称不能为空' }]"
            >
              <el-input
                v-model="saveForm.curveName"
                maxlength="40"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="数据日期："
              prop="dataDate"
              :rules="[
                { required: true, message: '数据日期不能为空' },
                { validator: this.dateValid, trigger: 'blur' }
              ]"
            >
              <el-date-picker
                v-model="saveForm.dataDate"
                placeholder="请选择日期"
                value-format="yyyy-MM-dd"
                style="width:100%"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col
            :span="24"
            v-for="(item, idx) in forDataList"
            :key="item.TERM_ID"
          >
            <el-form-item
              :label="item.TERM_VALUE + termTypes[item.TERM_UNIT] + '：'"
              :prop="'DATA' + (idx + 1)"
              :rules="[
                { required: true, message: '该项不能为空', trigger: 'blur' },
                {
                  pattern: /(^[0-9]{1,3}$)|(^[0-9]{1,3}[\.]{1}[0-9]{1,6}$)/,
                  message: '只能输入整数小于三位，小数小于六位的数字',
                  trigger: 'blur'
                }
              ]"
            >
              <el-input
                v-model="saveForm['DATA' + (idx + 1)]"
                maxlength="40"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="saveFunc" v-if="saveFlg!=3">确 定</el-button>
        <el-button @click="addOrEdit = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { publicManage_pub } from "@/api/index";

export default {
  data() {
    return {
      filterText: "", // 节点过滤关键字
      userName: "", //右侧用户名
      userDo: "授权角色", // 右侧用户行为
      userDoFlag: 0,
      addOrEdit: false, // 新增/编辑/查看弹窗
      saveFlg: 1, // 1:新增，2：编辑，3查看,
      saveTitles: ["添加曲线维护", "编辑曲线维护"],
      // dueSpotFlagList: [],
      // 机构树
      orgList: [
        {
          value: "01",
          label: "一级机构",
          children: [{ value: "001", label: "二级机构" }]
        }
      ],
      termTypes: {
        D: "日",
        M: "月",
        Y: "年"
      },
      // 右侧树data
      treeData: [],
      defaultProps: {
        children: "children",
        label: "curveName"
      },

      searchForm: {
        dataDate: "",
        page: 1,
        size: 15
      },
      total: 0,
      saveForm: {
        curveId: "",
        dataDate: "",
        curveCode: "",
        curveName: "",
        curveType: "",
        structCode: "",
        currencyCode: ""
      },
      checkList: [],
      // 完整表头字段&&列属性配置
      textData: [
        { prop: "curveId", label: "曲线编码" },
        { prop: "curveName", label: "曲线名称" },
        { prop: "dataDate", label: "数据日期 " },
        { prop: "affirmDate", label: "确认日期" }
      ],
      // 动态数据
      forDataList: [],
      // 获取table的数据
      tableData: []
    };
  },
  created() {
    this.checkListInit();
    // this.getAllDict();
    this.getCurves();
  },
  computed: {
    columnState() {
      console.log(this.checkList);
      let arr = [],
        arr1 = this.textData,
        arr2 = this.checkList;
      for (let i = 0; i < arr1.length; i++) {
        let flg = false;
        for (let j = 0; j < arr2.length; j++) {
          if (arr1[i].label === arr2[j]) {
            flg = true;
          }
        }
        arr.push(flg);
      }
      return arr;
    }
  },
  mounted() {
  },
  watch: {
     addOrEdit() {
      // 窗口打开或关闭清除校验结果
      if (this.$refs.saveForm) {
        this.$refs.saveForm.clearValidate();
      }
    },
  },
  methods: {
    rendertree(h, { node, data, store }) {
      return <span title={data.curveName}>{data.curveName}</span>;
    },
    filterTree() {
      this.$refs.configTree.$tree.filter(this.filterText);
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    checkListInit() {
      this.checkList = this.textData.map(v => {
        return v.label;
      });
    },
    searchFunc() {
      let data = {
        ...this.searchForm,
        curveCode: this.treeRow.curveCode,
        structCode: this.treeRow.termStructDef.structureCode
      };
      console.log(this.searchForm);
      // 查询循环项
      publicManage_pub
        .curveDataQueryStructList({ structCode: data.structCode })
        .then(res => {
          if (res) {
          // 排序
          let arr1 = [],arr2=[],arr3=[]
          res.forEach(e => { if(e.TERM_UNIT=='D'){arr1.push(e)} });
          res.forEach(e => { if(e.TERM_UNIT=='M'){arr2.push(e)} });
          res.forEach(e => { if(e.TERM_UNIT=='Y'){arr3.push(e)} });
          arr1 = arr1.sort((x,y)=>(x.TERM_VALUE-y.TERM_VALUE));
            arr2 = arr2.sort((x,y)=>(x.TERM_VALUE-y.TERM_VALUE));
            arr3 = arr3.sort((x,y)=>(x.TERM_VALUE-y.TERM_VALUE));
            this.forDataList = [...arr1,...arr2,...arr3];
          }
        });
      // 查询table
      publicManage_pub.curveDataQuery(data).then(res => {
        if (res.code == 200) {
          this.tableData = res.data;
          this.total = res.count;
        }
      });
    },
    addFunc() {
      if(!this.treeRow||!this.treeRow.curveCode)return this.$message.warning('请在曲线列表选择一条曲线，再新增')
      this.saveFlg = 1;
      for (let k in this.saveForm) {
        this.saveForm[k] = "";
      }
      this.addOrEdit = true;
      this.saveForm.curveId = "";
      this.saveForm.dataDate = "";
      this.saveForm.curveCode = this.treeRow.curveCode;
      this.saveForm.curveName = this.treeRow.curveName;
      this.saveForm.currencyCode = this.treeRow.dimCurrency.currencyCode;
      this.saveForm.curveType = this.treeRow.curveType;
      this.saveForm.structCode = this.treeRow.termStructDef.structureCode;
    },
    editFunc() {
      this.saveFlg = 2;
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据进行修改");
      }
      let row = selection[0];
      if (row.AFFIRM_FLAG == "1")
        return this.$message.warning("已确认曲线不能编辑");
      // let form = { ...row };
      // this.saveForm = form;
      this.saveForm.curveId = row.CURVE_ID;
      this.saveForm.curveName = row.CURVE_NAME;
      this.saveForm.curveCode = row.CURVE_CODE;
      this.saveForm.dataDate = row.DATA_DATE;
      this.saveForm.curveType = this.treeRow.curveType;
      this.saveForm.structCode = row.STRUCTURE_CODE;
      this.saveForm.affirmFlag = row.AFFIRM_FLAG;
      this.saveForm.currencyCode = this.treeRow.dimCurrency.currencyCode;
      // 回显DATA1到n
      for (const key in row) {
        if (key.indexOf("DATA") != -1) {
          this.$set(this.saveForm, key, (row[key] * 100).toFixed(6) + "");
        }
      }
      this.addOrEdit = true;
    },
    viewFunc() {
      this.saveFlg = 3;
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据进行查看");
      }
      let row = selection[0];
      this.saveForm.curveId = row.CURVE_ID;
      this.saveForm.curveName = row.CURVE_NAME;
      this.saveForm.curveCode = row.CURVE_CODE;
      this.saveForm.dataDate = row.DATA_DATE;
      this.saveForm.structCode = row.STRUCTURE_CODE;
      this.saveForm.currencyCode = this.treeRow.dimCurrency.currencyCode;
      // 回显DATA1到n
      for (const key in row) {
        if (key.indexOf("DATA") != -1) {
          this.$set(this.saveForm, key, (row[key] * 100).toFixed(2) + "");
          // this.saveForm[key] = row[key]*100+''
        }
      }
      this.addOrEdit = true;
    },
    delFunc() {
      let selection = this.$refs.multipleTable.selection;
      let str = "删除";
      if (selection.length < 1) {
        return this.$message.warning(`请选择要${str}的曲线`);
      }
      this.$confirm(`确定要${str}所选曲线吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          // 判断是否包含已确认曲线
          let delFlg = true;
          for (let i = 0; i < selection.length; i++) {
            if (selection[i].AFFIRM_FLAG == "1") {
              delFlg = false;
              break;
            }
          }
          if (!delFlg) return this.$message.warning("已确认曲线不能删除,请重新选择");
          let data = {
            curveCode: this.treeRow.curveCode,
            ids: selection.map(v => v.CURVE_ID)
          };
          publicManage_pub.curveDataDelete(data).then(res => {
            if (res.code == 200) {
              this.$message.success(str + "成功");
              this.searchFunc();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消" + str
          });
        });
    },
    startOrBackFunc(num) {
      let selection = this.$refs.multipleTable.selection;
      let str = num == 1 ? "确认" : "取消确认";
      if (selection.length < 1) {
        return this.$message.warning(`请选择要${str}的曲线`);
      }
      this.$confirm(`确定要${str}所选曲线吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let data = {
            affirmFlag: num + "",
            ids: selection.map(v => v.CURVE_ID)
          };
          publicManage_pub.curveDataChangeCurveStatus(data).then(res => {
            if (res.code == 200) {
              this.$message.success(str + "成功");
              this.searchFunc();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消" + str
          });
        });
    },
    // 即期计算
    spotCalculation() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length != 1) {
        return this.$message.warning("请选择一条数据");
      }
      let data = {
        curveCode: selection[0].CURVE_CODE,
        structCode: selection[0].STRUCTURE_CODE
      };
      publicManage_pub.curveDataSpotCalculation(data).then(res => {
        if (res) {
        }
      });
    },
    handleNodeClick(obj) {
      // 单选处理
      let node = { ...obj };
      if (!node.termStructDef) return;
      this.$refs.configTree.$tree.setCheckedNodes([]);
      this.$refs.configTree.$tree.setCheckedNodes([node]);
      this.treeRow = node;
      this.searchFunc();
    },
    caliberProjectNameFormatter(row) {
      return row.caliberProject.caliberProjectName;
    },
    // 点击表格右侧显示为xx授权
    authorizeFor(row) {
      this.$refs.multipleTable.toggleRowSelection(row, true);
      this.userName = row.roleName;
    },
    saveConfigTree() {},
    saveConfigTable() {},
    sizeChange(val) {
      this.searchForm.size = val;
      console.log(`每页 ${val} 条`);
      this.searchFunc();
    },
    pageChange(val) {
      this.searchForm.page = val;
      console.log(`当前页: ${val}`);
      this.searchFunc();
    },
    // 获取曲线列表
    getCurves() {
      publicManage_pub.curveDataGetCurveList().then(res => {
        if (res.code == 200) {
          let list = res.datas;
          // 根据curveType处理parentId
          for (let i = 0; i < list.length; i++) {
            if (list[i].curveType) {
              list[i].parentId = list[i].curveType;
            }
          }
          for (let i = 0; i < list.length; i++) {
            if (list[i].parentId == null && list[i].curveType) {
              list[i].parentId = list[i].curveType;
            }
            if(list[i].curveName=='曲线列表'||list[i].curveName=='基础曲线'||list[i].curveName=='合成曲线'){
              list[i].disabled = true;
            }
          }
          this.treeData = this.$listToTree("curveCode", "parentId", list);
          this.$nextTick(() => {
            // 默认选中的曲线，有
            this.handleNodeClick(list[2]);
          });
        }
      });
    },
    // 日期重复性校验
    dateValid(rule, value, callback) {
      let data = {
        curveId: this.saveForm.curveId,
        curveCode: this.saveForm.curveCode,
        dataDate: value
      };
      publicManage_pub.curveDataCheckData(data).then(res => {
        if (res.success) {
          callback(new Error("日期重复"));
        } else {
          callback();
        }
      });
    },
    saveFunc() {
      this.$refs["saveForm"].validate(valid => {
        if (valid) {
          let data = this.saveForm;
          let curveYieldData = "";
          for (let i = 0; i < this.forDataList.length; i++) {
            curveYieldData +=
              this.forDataList[i].TERM_ID + "@" + data["DATA" + (i + 1)] + ";";
          }
          let param = {
            currencyCode: data.currencyCode,
            curveCode: data.curveCode,
            curveId: data.curveId,
            curveName: data.curveName,
            curveType: data.curveType,
            dataDate: data.dataDate,
            structCode: data.structCode,
            affirmFlag: data.affirmFlag,
            curveYieldData: curveYieldData
          };
          publicManage_pub.curveDataSave(param).then(res => {
            if (res.code == 200) {
              this.$message.success("保存成功");
              this.searchFunc();
              this.addOrEdit = false;
            } else {
              this.$message.error(res.message || "保存失败");
            }
          });
        }
      });
    },
        
 
  }
};
</script>

<style lang="scss" scoped>
.top-title {
  font-size: 14px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #000000;
  line-height: 20px;
  vertical-align: middle;
  margin-top: 9px;
}
.vertical-bar {
  line-height: 20px;
  font-weight: 500px;
}
</style>